import os
import shutil
import tkinter as tk
from tkinter import filedialog
##############################
import basicConfig
from src import logPro

# 上传文件夹目录
files_up_dir = basicConfig.ASC_FILE_DIR


class FileUploader:

    def __init__(self, target_folder=files_up_dir, initial_dir="C:/"):
        # 初始化目标文件夹和初始目录
        self.target_folder = target_folder
        self.initial_dir = initial_dir
        self.ensure_target_folder_exists()

    def ensure_target_folder_exists(self):
        # 确保目标文件夹存在
        if not os.path.exists(self.target_folder):
            os.makedirs(self.target_folder)
            logPro.produce_logs("info", f"创建目标文件夹: {self.target_folder}")

    def select_files(self):
        # 打开文件选择对话框,允许用户选择一个或多个文件
        root = tk.Tk()
        root.withdraw()
        file_paths = filedialog.askopenfilenames(
            title="选择文件",
            filetypes=[("所有文件", "*.*")],
            initialdir=self.initial_dir  # 指定初始目录
        )
        return file_paths

    def upload_files(self, file_paths):
        # 将选中的文件复制到目标文件夹
        for file_path in file_paths:
            try:
                file_name = os.path.basename(file_path)
                target_path = os.path.join(self.target_folder, file_name)
                shutil.copy(file_path, target_path)
                logPro.produce_logs("info", f"文件 {file_name} 已上传到 {self.target_folder}")
            except Exception as e:
                logPro.produce_logs("error", f"上传文件 {file_name} 时出错: {e}")

    def run(self):
        # 运行文件上传流程
        file_paths = self.select_files()
        if file_paths:
            logPro.produce_logs("info", f"选择了 {len(file_paths)} 个文件")
            self.upload_files(file_paths)
        else:
            logPro.produce_logs("info", "没有选择任何文件")
